package com.LeeCode;

import java.util.Arrays;

/**
 * 剧情触发时间
 */

public class CodeLCP008 {
    public static void main(String[] args) {
        int[][] increase = {
                {6, 3, 4},
                {6, 7, 2}
        };

        int[][] requirements = {
                {0, 13, 14},
                {0, 5, 5},
                {0, 4, 18},
                {4, 3, 4}
        };
        System.out.println(Arrays.toString(new CodeLCP008().getTriggerTime(increase, requirements)));
    }

    public int[] getTriggerTime(int[][] increase, int[][] requirements) {
        int n = requirements.length;
        int[] ans = new int[n];
        int[] C = new int[increase.length + 1], R = new int[increase.length + 1], H = new int[increase.length + 1];
        for (int i = 0; i < increase.length; i++) {
            C[i + 1] = increase[i][0] + C[i];
            R[i + 1] = increase[i][1] + R[i];
            H[i + 1] = increase[i][2] + H[i];
        }

        for (int i = 0; i < n; i++) {
            int Cindex = lowerBound(C, requirements[i][0]);
            int Rindex = lowerBound(R, requirements[i][1]);
            int Hindex = lowerBound(H, requirements[i][2]);

            if (Cindex == increase.length + 1 || Rindex == increase.length + 1 || Hindex == increase.length + 1) {
                ans[i] = -1;
                continue;
            }
            int fast = Math.max(Cindex, Rindex);
            fast = Math.max(fast, Hindex);
            ans[i] = fast;
        }

        return ans;
    }

    private int lowerBound(int[] nums, int target) {
        int left = -1, right = nums.length;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target)
                right = mid;
            else
                left = mid;
        }
        return right;
    }
}
